package game.module.mail.dao;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import game.module.mail.bean.HallMailBean;

/**
 * @author: Pomelo.Lee
 * @date: 2017年8月24日 下午7:36:59
 */
public class MailCache {

	private static Logger logger = LoggerFactory.getLogger(MailCache.class);

	static class SingletonHolder {
		static MailCache instance = new MailCache();
	}

	public static MailCache getInstance() {
		return SingletonHolder.instance;
	}

	private Map<Integer, Map<Long, HallMailBean>> mailMapTemplateIdKey = new ConcurrentHashMap<>();

	public void loadFromDb(int playerId) {
		if (mailMapTemplateIdKey.get(playerId) != null) {
			return;
		}
		List<HallMailBean> listMail = MailDao.getInstance().getMailByPlayerId(playerId);
		// add cache with template id key
		Map<Long, HallMailBean> mailMapTemplateIdKeyOne = new ConcurrentHashMap<>();
		try {
			for (HallMailBean mail : listMail) {
				mailMapTemplateIdKeyOne.put(mail.getId(), mail);
			}
			mailMapTemplateIdKey.put(playerId, mailMapTemplateIdKeyOne);
		} catch (Exception e) {
			logger.error("", e);
		}
	}

	public Map<Long, HallMailBean> getMailByPlayerId(int playerId) {
		return mailMapTemplateIdKey.get(playerId);
	}

	public void addNew(int playerId, HallMailBean mail) {
		Map<Long, HallMailBean> mailMap = getMailByPlayerId(playerId);
		if (mailMap != null) {
			mailMap.put(mail.getId(), mail);
		}
	}

	public void remove(int playerId) {
		logger.info("remove play packback cache!");
		mailMapTemplateIdKey.remove(playerId);
	}
	
	public boolean removeMail(int playerId, long id) {
		Map<Long, HallMailBean> mailMap = getMailByPlayerId(playerId);
		if (mailMap != null && mailMap.containsKey(id)) {
			mailMap.remove(id);
			return true;
		}
		return false;
	}

}
